package com.sihan.swvp.common;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

import javax.imageio.ImageIO;

import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class SvgUtil {
	public static byte[] draw2png(byte[] img, JSONObject jdraw) {

		ByteArrayInputStream bin = null;
		ByteArrayOutputStream out = null;
		try {
			bin = new ByteArrayInputStream(img);
			BufferedImage iamge = javax.imageio.ImageIO.read(bin);
			Graphics2D graph = (Graphics2D) iamge.getGraphics();

			JSONArray draws = jdraw.getJSONArray("draw");
			for (int i = 0; i < draws.size(); i++) {
				JSONObject draw = draws.getJSONObject(i);
				if ("rect".equals(draw.get("type"))) {// 矩形
					double x = CommonUtil.o2double(draw.get("x"));
					double y = CommonUtil.o2double(draw.get("y"));
					double w = CommonUtil.o2double(draw.get("width"));
					double h = CommonUtil.o2double(draw.get("height"));
					String stroke = CommonUtil.o2string(draw.get("stroke"));
					Rectangle2D rectangle = new Rectangle2D.Float();
					rectangle.setRect(x, y, w, h);
					graph.setColor(String2Color(stroke));
					graph.setStroke(new BasicStroke(CommonUtil.o2int(draw
							.get("strokewidth")), BasicStroke.CAP_SQUARE,
							BasicStroke.JOIN_ROUND));
					graph.draw(rectangle);
				} else if ("ellipse".equals(draw.get("type"))) {// 椭圆
					double x = CommonUtil.o2double(draw.get("x"));
					double y = CommonUtil.o2double(draw.get("y"));
					double w = CommonUtil.o2double(draw.get("radiusX"));
					double h = CommonUtil.o2double(draw.get("radiusY"));
					Ellipse2D ellipse = new Ellipse2D.Double(x, y, w, h);
					String stroke = CommonUtil.o2string(draw.get("stroke"));
					graph.setColor(String2Color(stroke));
					graph.setStroke(new BasicStroke(CommonUtil.o2int(draw
							.get("strokewidth")), BasicStroke.CAP_SQUARE,
							BasicStroke.JOIN_ROUND));
					graph.draw(ellipse);
				} else if ("text".equals(draw.get("type"))) {// 文字
					double x = CommonUtil.o2double(draw.get("x"));
					double y = CommonUtil.o2double(draw.get("y"));
					String text = CommonUtil.o2string(draw.get("text"));
					String fill = CommonUtil.o2string(draw.get("fill"));
					if (fill.indexOf("#") == -1) {// 两种不通的颜色规格，根据#判断
						String getSignInfo = fill.substring(
								fill.indexOf("(") + 1, fill.indexOf(")"));
						String[] c = getSignInfo.split(",");
						Integer r = CommonUtil.o2int(c[0].trim());
						Integer g = CommonUtil.o2int(c[1].trim());
						Integer b = CommonUtil.o2int(c[2].trim());
						graph.setColor(new Color(r, g, b));
					} else {
						graph.setColor(String2Color(fill));
					}

					DecimalFormat df = new DecimalFormat("######0"); // 四色五入转换成整数

					String font = CommonUtil.o2string(draw.get("font"));
					String[] fArr = font.split(" ");
					Font f = new Font(null, 0, CommonUtil.o2int(fArr[0]
							.replace("px", "")));
					graph.setFont(f);// 设置字体
					graph.drawString(text, CommonUtil.o2int(df.format(x)),
							CommonUtil.o2int(df.format(y)));
				}
			}

			out = new ByteArrayOutputStream();
			ImageIO.write(iamge, "jpg", out);
			byte[] b = out.toByteArray();

			return b;
		} catch (IOException e) {

			e.printStackTrace();
		} finally {

			CommonUtil.close(bin);
			CommonUtil.close(out);
		}

		return null;
	}

	/**
	 * Color对象和十六进制颜色编码之间的转换
	 * 
	 * @param str
	 * @return
	 */
	public static Color String2Color(String str) {
		int i = Integer.parseInt(str.substring(1), 16);
		return new Color(i);
	}

	public static byte[] svg2ipng(String svg) {
		ByteArrayOutputStream out = null;
		byte[] rst = null;
		try {
			byte[] bytes = svg.getBytes("utf-8");
			PNGTranscoder t = new PNGTranscoder();
			TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(bytes));
			out = new ByteArrayOutputStream();
			TranscoderOutput output = new TranscoderOutput(out);
			t.transcode(input, output);
			rst = out.toByteArray();
		} catch (Exception e) {
			// TODO: handle exception
		}
		finally{
			CommonUtil.close(out);
		}

		return rst;
	}

	// public static byte[] svg2png(String svg){
	// try {
	// Document doc = Jsoup.parse(svg);
	// Elements svgs = doc.getElementsByTag("svg");
	// Element svgel = svgs.get(0);
	// Elements imgs = svgel.getElementsByTag("image");
	// Element img = imgs.get(0);
	// String url = img.attr("xlink:href");
	// URL input = new URL("http://localhost:8088/swvp/"+url);
	// BufferedImage imge = javax.imageio.ImageIO.read(input);
	// Graphics2D graph = (Graphics2D) imge.getGraphics();
	// Elements rects = svgel.getElementsByTag("rect");
	// for (int i = 1; i < rects.size(); i++) {
	//
	// double x=0;
	// double y =0;
	// if(rects.get(i).attr("x") !=null && !"".equals(rects.get(i).attr("x"))){
	// x = Double.parseDouble(rects.get(i).attr("x").toString());
	// y = Double.parseDouble(rects.get(i).attr("y").toString());
	// }
	// double w = Double.parseDouble(rects.get(i).attr("width").toString());
	// double h = Double.parseDouble(rects.get(i).attr("height").toString());
	// Rectangle2D rectangle = new Rectangle2D.Float();
	// rectangle.setRect(x+100, y+100, w, h);
	// graph.setColor(Color.red);
	// // graph.setFont(font)
	// // rectangle.sets
	// graph.draw(rectangle);
	//
	// }
	//
	// Elements circles = svgel.getElementsByTag("circle");
	// for (Element circle : rects) {
	//
	// }
	//
	// Elements texts = svgel.getElementsByTag("text");
	// for (int z = 0;z < texts.size(); z++) {
	//
	// double x=0;
	// double y =0;
	// System.out.println(texts.get(z).attr("x")+"========================");
	// if(texts.get(z).attr("x") !=null && !"".equals(texts.get(z).attr("x"))){
	// x = Double.parseDouble(texts.get(z).attr("x").toString());
	// y = Double.parseDouble(texts.get(z).attr("dy").toString());
	// }
	// // double w =
	// Double.parseDouble(rects.get(z).attr("width").replace("px","").toString());
	// // double h =
	// Double.parseDouble(rects.get(z).attr("height").replace("px","").toString());
	// Rectangle2D rectangle = new Rectangle2D.Float();
	// rectangle.setRect(x, y, 0, 0);
	// // rectangle.setRect(r)
	//
	// graph.draw(rectangle);
	//
	// }
	//
	// ByteArrayOutputStream out = new ByteArrayOutputStream();
	// ImageIO.write(imge, "jpg", out);
	// byte[] b = out.toByteArray();
	//
	// return b;
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	//
	// return null;
	// }

}
